package com.example.springboot_05_variousresonse.controller;

import com.alibaba.fastjson.JSON;
import com.example.springboot_05_variousresonse.po.DemoRsp;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(path="data")
public class DataResqRest {
    /*
    返回文本
     */
   @ResponseBody
   @GetMapping(path="str")
    public String strRsq(){
       return "hello"+ UUID.randomUUID().toString();
   }

   @ResponseBody
   @GetMapping(path="str2")
    public void str2Rsq(HttpServletResponse response) throws IOException {
       Map<String ,String> ans = new HashMap<String,String>(2);
        ans.put("a","b");
        ans.put("c","d");
        response.getOutputStream().write(JSON.toJSONString(ans).getBytes());
        response.getOutputStream().flush();
   }
   /*
   返回POJO实体
    */
    @ResponseBody
    @GetMapping(path="bean")
    public DemoRsp beanRsq(){
        return new DemoRsp(200,"success",UUID.randomUUID().toString()+"--->data");
    }
    /*
    返回数组
     */
    @ResponseBody
    @GetMapping(path="array")
    public String[] array(){
        return new String[]{"a","b","c","d"};
    }
    /*
    返回html
     */
    @ResponseBody
    @GetMapping(path = "html")
    public String strHtmlRsp() {
        return "<html>\n" + "<head>\n" + "    <title>返回数据测试</title>\n" + "</head>\n" + "<body>\n" +
                "<h1>欢迎欢迎，热烈欢迎</h1>\n" + "</body>\n" + "</html>";
    }
    /**
     * 返回图片
     */
    @GetMapping(path = "img")
    public void imgRsp(HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        ServletOutputStream outStream = response.getOutputStream();

        String path = "https://spring.hhui.top/spring-blog/imgs/info/info.png";
        URL uri = new URL(path);
        BufferedImage img = ImageIO.read(uri);
        ImageIO.write(img, "png", response.getOutputStream());
        System.out.println("--------");
    }


}
